package gui;

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;

/**
 *	@(#)GameButton.java
 *
 *	The <code>GameButton</code> is an ordinary button that can have a
 *	transparent icon image.
 *
 *	@author Grzegorz Kobiela
 *	@version 1.0 2008/4/20
 */
public class GameButton
extends javax.swing.JButton
{
	/** The transparency. */
	private float alpha = 1.0f;

	/**
	 *	Creates a new <code>GameButton</code> instance.
	 */
	public GameButton() {
		setOpaque(false);
	}

	/**
	 *	Sets the transparency to the given alpha value.
	 *	@param alpha the transparency
	 */
	public void setAlpha(float alpha) {
		this.alpha = alpha;
	}

	/**
	 *	Sets the icon to the given value with the transparency
	 *	set at construction.
	 *	@param icon the new icon
	 */
	public void setIcon(ImageIcon icon) {
		if(icon != null) {
			int w = getWidth();
			int h = getHeight();
			BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
			Graphics2D g = img.createGraphics();
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
			g.drawImage(icon.getImage(), (w - icon.getIconWidth()) / 2, (h - icon.getIconHeight()) / 2, null);
			super.setIcon(new ImageIcon(img));
		} else {
			super.setIcon(null);
		}
	}

	/**
	 *	Returns the string representation.
	 *	@return the string representation
	 */
	@Override
	public String toString() {
		return String.format("%s [x=%d,y=%d,w=%d,h=%d]", getClass().getSimpleName(), getX(), getY(), getWidth(), getHeight());
	}
}